import React, { Component } from 'react'
import { Card, Button, Icon, Table, message, Modal, Form, Input } from 'antd'
import {connect} from 'react-redux'
import { reqCategoryList, reqCategoryAdd, reqCategoryUpdate } from '../../api/index'
import { createSaveCategoryAction} from '../../redux/actions/category_action'
import { PAGE_SIZE } from '../../config/index'
let { Item } = Form
@connect(
  state =>({}),
  {saveCategory:createSaveCategoryAction}
)
@Form.create()
class Category extends Component {


  state = {
    categoryList: [],
    visible: false,
    operType: '',
    isLoading: true,
    modalCurrentValue: '',
    modalCurrentId: '',
  }
  componentDidMount() {
    this.getCategory()
  }

  //打开弹窗
  showAdd = () => {
    this.setState({
      visible: true,
      operType: '新增分类',
      modalCurrentValue:'',
      modalCurrentId:''
    });
  };

  showUpdate = (item) => {
    const { _id, name } = item

    this.setState({
      visible: true,
      operType: '修改分类',
      modalCurrentValue: name,
      modalCurrentId: _id
    });
  };
  toAdd = async (values) => {
    let result = await reqCategoryAdd(values)

    let { status, data, msg } = result
    if (0 === status) {
      let categoryList = [...this.state.categoryList]
      categoryList.unshift(data)
      this.setState({ categoryList })
      this.props.form.resetFields()
      this.setState({ visible: false, });
      message.success('添加成功', 1)

    }
    if (1 === status) {

      message.error('添加失败，错误信息：' + msg, 1)

    }
  }
  toUpdate = async (categoryObj) => {

    let result = await reqCategoryUpdate(categoryObj)

    const { status, msg } = result
    if (0 === status) {
      this.getCategory()
      this.props.form.resetFields()
      this.setState({ visible: false,});
      message.success('更新成功', 1)
    }
    if (1 === status) {

      message.error('添加失败，错误信息：' + msg, 1)

    }
  }
  //点击确定回调
  handleOk = () => {
    let { operType } = this.state
    this.props.form.validateFields((err, values) => {
      if (err) {
        message.warning('输入有误,请检查', 1)
        return
      }
      if ('新增分类' === operType) this.toAdd(values)

      if ('修改分类' === operType) {
        const categoryId = this.state.modalCurrentId
        const categoryName = values.categoryName
        const categoryObj = { categoryId, categoryName }
        this.toUpdate(categoryObj)
      }
    })
  };
  //点击取消回调
  handleCancel = () => {
    this.setState({
      visible: false,
    });
    this.props.form.resetFields()
  };


  getCategory = async () => {
    let result = await reqCategoryList()
    this.setState({ isLoading: false })
    let { status, data, msg } = result

    if (0 === status) {
      this.setState({ categoryList: data.reverse() })
      //存入redux 便于之后调用
      this.props.saveCategory(data)
    } else {
      message.error(msg)
    }
  }
  render() {

    let { getFieldDecorator } = this.props.form
    const columns = [
      {
        title: '分类',
        dataIndex: 'name',
        key: 'name',
      },
      {
        title: '操作',
        //写这个就传入  age 不写就全部都传过去
        // dataIndex: 'age',
        key: 'age',
        render: (item) => { return <Button type='link' onClick={() => { this.showUpdate(item) }}>修改</Button> },
        width: '25%',
        align: 'center'
      },
    ];
    return (
      <div>
        <Card title=""
          extra=
          {<Button type='primary' onClick={this.showAdd}>
            <Icon type='plus' />
          添加
          </Button>}>
          <Table
            dataSource={this.state.categoryList}
            columns={columns}
            bordered
            rowKey='_id'
            pagination={{ pageSize: PAGE_SIZE, showQuickJumper: true }}
            loading={this.state.isLoading}
          />
        </Card>
        <Modal
          title={this.state.operType}
          visible={this.state.visible}
          okText='确定'
          cancelText='取消'
          onOk={this.handleOk}
          onCancel={this.handleCancel}
        >
          <Form onSubmit={this.handleSubmit} className="login-form">
            <Item>
              {getFieldDecorator('categoryName', {
                //设置默认值
                initialValue: this.state.modalCurrentValue,
                rules: [
                  { required: true, message: '不能为空' },
                ],
              })(
                <Input
                  placeholder="分类"
                />,
              )}

            </Item>
          </Form>
        </Modal>
      </div>
    )
  }
}
export default Category